using System;
using System.Collections.Generic;
using System.Text;

namespace csammisrun.OscarLib.Utility
{
  /// <summary>
  /// Provides much the same functionality as <see cref="Marshal"/>, but in
  /// little-endian format and not network byte order (like every other part of
  /// the OSCAR protocol except for ICQ, cool!)
  /// </summary>
  internal static class MarshalLE
  {
    public static ushort ByteArrayToUshort(byte[] buffer, ref int index)
    {
      ushort retval = (ushort)((buffer[index + 1] << 8) | buffer[index]);
      index += 2;
      return retval;
    }

    public static uint ByteArrayToUint(byte[] buffer, ref int index)
    {
      uint retval = (uint)(
        (buffer[index + 3] << 24) |
        (buffer[index + 2] << 16) |
        (buffer[index + 1] << 8) |
        buffer[index]);
      index += 4;
      return retval;
    }

    /// <summary>
    /// Writes an unsigned short (two bytes) into an array
    /// </summary>
    /// <param name="buffer">A byte buffer</param>
    /// <param name="u">An unsigned short</param>
    /// <param name="index">The index at which to write the two bytes</param>
    public static void InsertUShort(byte[] buffer, ushort u, ref int index)
    {
      buffer[index++] = (byte)(u & 0x00FF);
      buffer[index++] = (byte)(u & 0xFF00);
    }

    /// <summary>
    /// Writes an unsigned int (four bytes) into an array
    /// </summary>
    /// <param name="buffer">A byte buffer</param>
    /// <param name="u">An unsigned int</param>
    /// <param name="index">The index at which to write the four bytes</param>
    public static void InsertUint(byte[] buffer, uint u, ref int index)
    {
      buffer[index++] = (byte)(u & 0x000000FF);
      buffer[index++] = (byte)(u & 0x0000FF00);
      buffer[index++] = (byte)(u & 0x00FF0000);
      buffer[index++] = (byte)(u & 0xFF000000);
    }
  }
}
